﻿using Grow.Domain.Repository.CreateDomainRepository;
using Grow.Domain.Repository.EntityFrameworkCore.SqlServer.CreateDomainRepository;
using Grow.Module;
using Grow.Module.Service;
using Grow.Utils.Exceptions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Grow.Domain.Repository.EntityFrameworkCore.SqlServer
{
    public abstract class RepositorySqlServerModuleBase : ModuleBase, IDomainRepositoryModule
    {
        public override ModuleLevel Level => ModuleLevel.Framework;
        public override void AddDependModule(IDependModuleBuilder dependModuleBuilder)
        {
        }

        public override void AddService(IServiceContainer serviceContainer)
        {
            CreateDomainRepositoryBuilder createDomainRepositoryBuilder = new(serviceContainer);
            CreateDomainRepository(createDomainRepositoryBuilder);
            serviceContainer.BuilderManager.SetBuilder<ICreateDomainRepositoryBuilder>(createDomainRepositoryBuilder);

            _ = serviceContainer.ServiceCollection.AddScoped<IUnitOfWorkManager, SqlServerUnitOfWorkManager>();
            _ = serviceContainer.ServiceCollection.AddScoped<IUnitOfWork, UnitOfWork>();

            _ = serviceContainer.ServiceCollection.AddDbContext<IDbContext, SqlServerDbContext>((a, b) =>
            {
                IServiceContext serviceContext = a.GetRequiredService<IServiceContext>();
                UnitOfWorkOptions dbOptions = serviceContext.GetOptions<UnitOfWorkOptions>();
                if (string.IsNullOrEmpty(dbOptions.ConnectionString))
                {
                    throw new GrowFrameworkException($"{nameof(dbOptions)}：ConnectionString 为空");
                }
                _ = b.UseSqlServer(dbOptions.ConnectionString, c =>
                {
                    _ = c.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
                    _ = c.MigrationsAssembly(dbOptions.MigrationsAssembly);
                });
            });
        }

        public abstract void CreateDomainRepository(ICreateDomainRepositoryBuilder createDomainRepositoryBuilder);

        public override void UseService(IServiceContext serviceContext)
        {
        }


    }
}
